package com.example.demo.module.mq;

import com.example.demo.entity.Order;
import com.example.demo.service.SeckillService;
import com.example.demo.service.shop.OrderService;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 通过MQ创建订单，并保存用户ID和订单ID到redis
 */
@Component
@RabbitListener(queues = "create_order_queue")//监听消息队列
public class CreateOrderReceiver {
    @Resource
    private OrderService orderService;
    @Resource
    private SeckillService seckillService;
    @RabbitHandler//@RabbitHandler来实现具体消费
    public void QueueReceiver(Order order) {
        try {
            System.out.println("收到订单创建消息，准备保存订单 : " + order.getOrderNo());
            orderService.createOrder(order);//写到数据
            System.out.println("保存订单成功：" + order.getId());
            //保存信息到缓存，以便通知用户订单创建成功
            seckillService.saveOrderId(order);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}